import { Button, Form, Input, Modal, DatePicker, Table, Select, Image, Switch, Checkbox, message, Spin } from "antd"

import { PlusOutlined, DeleteOutlined, SearchOutlined, EditOutlined, EyeOutlined } from "@ant-design/icons"
import { useState, useEffect, ReactNode, Fragment } from "react"
import "./category.css"
import MyModal from "@/components/myModal"
import { getCategoryApi, addCategory, deleteCategory, updateCategory } from '@/api/category';

import { FormInstance } from "rc-field-form"
//声明表格数据的类型
type Idata = {
    categoryImgurl?: string
    category_id: string;
    ccategoryName: string;
    createTime: string;
    creator: string
    updateTime: string;
    updator: string;
    key?: string
    _id: string;
    imageUrl?: string
}

//声明表格每一列的数据
type Icolumns = {
    align?: any;
    dataIndex: string;
    title: string;
    width?: string | number;
    key?: string,
    render?: (value: any, record: Idata, index: number) => ReactNode | any
}

const ProductList = () => {
    //声明一个要记录要被删除的商品id状态
    let [delId, setDelId] = useState<string | undefined>()
    //控制普通modal显示和隐藏
    let [isModalOpen, setIsModalOpen] = useState<boolean>()
    //记录当前的modal选择器中category_id
    let [currentCategoryId, setCurrentCategoryId] = useState<string | undefined>("")
    //标记点击了modal的确认按钮后是编辑还是增加 add/edit
    let [actionType, setActionType] = useState("add")
    //form中默认选择的内容
    let [selectValue, setSelectValue] = useState<{ label: string, value: string } | null>(null)
    //声明Form实例
    let [modalForm] = Form.useForm()
    //控制加载动画
    let [tableLoading, setTableLoading] = useState<boolean>(false)
    //控制modal弹框的标题
    let [modalTitle, setModalTitle] = useState('')
    //控制Modal显示和隐藏
    let [modalOpen, setModalOpen] = useState<boolean>(false)
    //声明表格数据
    let [dataSource, setDataScource] = useState<Idata[]>([])
    //声明编辑数据的方法
    let edit = async (record: Idata & { category_realId?: string }) => {
        //打开Modal对话框
        setModalOpen(true)
        //浅拷贝record
        let newRecord: Idata = { ...record }
        //由于封装的组件,回显字段是imageUrl,而数据record是categoryImgurl,所以要处理一下
        delete newRecord.categoryImgurl
        newRecord.imageUrl = record.categoryImgurl;
        console.log(newRecord)
        // new
        //设置回显数据
        modalForm.setFieldsValue(newRecord)

        //设置当前被编辑的id

        setCurrentCategoryId(record.category_id)

        setModalTitle('修改类目')

    }
    //删除产品
    let handleDelete = async (record: any) => {
        // console.log(record)
        setDelId(record.category_id)
        //弹窗
        setIsModalOpen(true)
    }
    //声明列数据
    let columns: Icolumns[] = [
        {
            width: 70,
            title: "选择",
            dataIndex: 'check',
            align: 'center',
            render() {
                return <Checkbox></Checkbox>
            }
        },
        {
            align: 'center',
            title: "类目图片",
            width: 100,
            dataIndex: 'categoryImgurl',
            key: 'categoryImgurl',
            render(_) {
                return (<Image
                    width={50}
                    src={_}
                />)
            }
        },
        {
            align: 'center',
            title: "类目编号",
            dataIndex: 'category_id',
            key: 'category_id'
        },
        {
            align: 'center',
            title: '类目名称',
            dataIndex: 'categoryName',
            key: 'categoryName'
        },
        {
            align: 'center',
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime'
        },
        {
            align: 'center',
            title: '创建人',
            dataIndex: 'creator',
            key: 'creator'
        },
        {
            align: 'center',
            title: '修改时间',
            dataIndex: 'updateTime',
        },
        {
            align: 'center',
            title: '修改人',
            dataIndex: 'updator'
        },
        {
            align: 'center',
            title: '操作',
            dataIndex: 'action',
            render(_, record) {
                // console.log(_)
                // console.log(record)//当前列的数据
                return (
                    <Fragment>
                        <Button icon={<EyeOutlined />}>查看</Button>
                        <Button icon={<EditOutlined />} onClick={
                            () => {
                                edit(record)
                                //标记点击按钮的类型是编辑
                                setActionType('edit')
                            }
                        }>编辑</Button>
                        <Button danger
                            onClick={
                                () => {
                                    handleDelete(record)
                                }
                            }
                            icon={<DeleteOutlined />}>删除</Button>
                    </Fragment>
                )
            },
            key: 'action'
        }
    ]

    //获取产品列表

    let getCategory = () => {
        //打开加载动画
        setTableLoading(true)
        getCategoryApi()
            .then(res => {
                // console.log(res)
                //因为dataSource中必须要定义key,所以使用map进行处理,增加一个key
                let data = res.data.data.map((item: Idata): Idata & { key: string } => {
                    return {
                        key: item._id as string,
                        ...item,
                        updator: item.updator ?? '暂无',
                        updateTime: item.updateTime ?? '暂无修改'
                    }
                }).reverse()
                setDataScource(data)
                //关闭加载动画
                setTableLoading(false)
            })
    }

    //发起请求,获取列表数据
    useEffect(() => {
        //dom挂载之后,请求数据
        getCategory()
    }, [])

    //确定按钮,并且表单校验通过的回调
    let handleOnok = async (form: FormInstance | undefined) => {
        //获取modal表单中的数据
        let formData = form?.getFieldsValue();
        // console.log(formData) {imageUrl:xxx,categoryName:xxx}
        //传给后台的参数是 {categoryImgurl:xxx,categoryName:xxx}
        //所以要把imageUrl字段改成categoryImgurl就行了,下面是一些简单处理
        //浅拷贝formData
        let newData = { ...formData }
        //删除imageUrl属性
        delete newData.imageUrl;
        //换成categoryImgurl
        newData.categoryImgurl = formData.imageUrl;
        //当前是增加操作
        if (actionType === 'add') {
            try {
                let res = await addCategory(newData)
                // console.log(res)
                setModalOpen(false)
                //更新数据
                getCategory()
                //全局添加成功的提示
                res.data.state && message.success('添加成功')
            } catch (e) {
                console.log(e)
            }
        } else if (actionType === 'edit') {
            newData.category_id = currentCategoryId;
            try {
                //调用修改商品信息接口
                let res = await updateCategory(newData);
                console.log(res)
                //关闭modal
                setModalOpen(false)
                if (res.data.state) {
                    //全局提示
                    message.success('修改成功')
                }
                //更新列表
                getCategory()
            } catch (e) {
                console.log(e)
            }

        }
        //清空表单数据
        form?.resetFields()
    }

    //取消按钮的回调

    let handleOncancel = (form: FormInstance | undefined) => {
        console.log(form)
        setModalOpen(false)
        //清除Form实例上的data数据
        form?.resetFields()
        message.warning('已取消')
    }

    //普通对话框方法



    //确定按钮
    let handleOk = async () => {
        try {
            let res = await deleteCategory(delId as string);
            // console.log(res)
            if (res.data.state) {
                message.success('删除成功')
            }
            //更新列表
            getCategory();
            //关闭弹框
            setIsModalOpen(false)
        } catch (e) {
            console.log(e)
        }
    }
    let handleCancel = () => {
        setIsModalOpen(false)
        message.warning('已取消删除')
    }

    return (
        <div className="list_container">
            {/* 确认对话框 */}
            <Modal title="删除提示" okText='确认删除' centered cancelText='取消删除' open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <p>是否要删除这条数据?</p>
            </Modal>
            {/* 表单对话框 */}
            <MyModal formInstance={modalForm} title={modalTitle} open={modalOpen} onOk={handleOnok} onCancel={handleOncancel}>
                <Form.Item
                    label="类目名称"
                    name="categoryName"
                    rules={[{ required: true, message: '请输入商品名称' }]}
                >
                    <Input />
                </Form.Item>
            </MyModal>
            <div className="tip">
                <p className="tip_top">操作提示</p>
                <ul>
                    <li>1.这里是类目操作</li>
                    <li>2.不要删除vip类目,没有权限</li>
                </ul>
            </div>
            {/* 中间操作部分 */}
            <div className="operation">
                <div className="button">
                    <Button type="primary" icon={<PlusOutlined />} onClick={() => {
                        setModalOpen(true)
                        setModalTitle('添加商品')
                        setActionType('add')
                    }}>添加类目</Button>

                </div>
            </div>
            {/* 表格部分 */}
            <div className="table">
                <Spin spinning={tableLoading} tip='正在加载数据...'>
                    <Table bordered dataSource={dataSource}
                        pagination={{ position: ['bottomCenter'], pageSize: 10 }}
                        scroll={{ y: 400 }}
                        columns={columns}></Table>
                </Spin>
            </div>
        </div >
    )

}

export default ProductList